<template>
  <div>

      <van-row>
        <van-col span="10">
          <van-icon name="arrow-left" @click="fan"/>
        </van-col>
        <van-col span="8">
         {{otherUserName}}
        </van-col>
        <van-col span="4">
        </van-col>

      </van-row>
  </div>
  <div class="chat-container">
    <!-- 聊天消息区域 -->
    <div class="message-list" ref="messageList">
      <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message-item', { 'own-message': message.isOwn }]"
      >
        <!-- 对方头像 -->
        <van-image
            v-if="!message.isOwn"
            round
            width="40"
            height="40"
            :src="otherUserAvatar"
            class="avatar"
        />

        <!-- 消息内容 -->
        <div class="message-content">
          <div class="message-info">
            <span v-if="!message.isOwn" class="username">{{ otherUserName }}</span>
            <span class="timestamp">{{ formatTime(message.timestamp) }}</span>
          </div>
          <div class="bubble">
            {{ message.content }}
            <div v-if="message.status === 'sending'" class="sending-status">
              <van-loading type="spinner" size="20px"/>
            </div>
            <van-icon
                v-if="message.status === 'error'"
                name="warning-o"
                color="#ee0a24"
                class="status-icon"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <van-form @submit="sendMessage" class="message-form">
        <div class="input-container">
          <van-field
              v-model="adk"
              rows="1"
              autosize
              type="textarea"
              placeholder="输入消息..."
              class="message-input"
              @keypress.enter.exact.prevent="sendMessage"
          />
          <van-button
              round
              type="primary"
              native-type="submit"
              :disabled="!adk.trim()"
              class="send-button"
          >
            发送
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted, nextTick} from 'vue'
import {Image as VanImage} from 'vant'
import axios from "axios";
import router from "@/router";

// 模拟数据
const otherUserName = ref('AI小蜜')
const otherUserAvatar = ref('https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg')
const adk = ref('')
// const adk2 = ref('')
const messageList = ref(null)
const fan = () => {
  router.push('/message')
}
// const userid = ref()
// const answer = ref('')
// 消息数据示例
const messages = ref([
  {
    content: '您好，我是智能AI小蜜，请问有什么可以帮您？',
    timestamp: new Date().getTime() - 60000,
    isOwn: false,
    status: 'sent'
  },
])

// 自动滚动到底部
// 修改后的scrollToBottom方法
const scrollToBottom = (behavior = 'smooth') => {
  nextTick(() => {
    if (messageList.value) {
      const container = messageList.value
      // 使用现代浏览器的scrollTo方法
      container.scrollTo({
        top: container.scrollHeight,
        behavior: behavior // 平滑滚动效果
      })
    }
  })
}

// 发送消息
const sendMessage = async () => {
  try {
    // 用户消息
    const userMessage = {
      content: adk.value,
      timestamp: new Date().getTime(),
      isOwn: true,
      status: 'sent'
    }

    messages.value.push(userMessage)
    scrollToBottom('auto') // 立即滚动

    // 清空输入
    const question = adk.value
    adk.value = ""

    // 发送请求
    const response = await axios.post('/user/DataManage/', {ask: question})

    // AI回复
    const aiMessage = {
      content: response.data.res,
      timestamp: new Date().getTime(),
      isOwn: false,
      status: 'sent'
    }

    messages.value.push(aiMessage)
    scrollToBottom('smooth') // 再次滚动

  } catch (error) {
    console.error('发送失败:', error)
    // 可以添加错误处理
  }
}

// 时间格式化
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// WebSocket连接（根据实际情况配置）
let socket = null
onMounted(() => {
  // socket = new WebSocket('wss://your-websocket-endpoint')
  // socket.onmessage = (event) => {
  //   const data = JSON.parse(event.data)
  //   messages.value.push({
  //     content: data.content,
  //     timestamp: new Date().getTime(),
  //     isOwn: false,
  //     status: 'sent'
  //   })
  scrollToBottom()
  // }
})

onUnmounted(() => {
  if (socket) socket.close()
})
</script>

<style scoped>
.chat-container {
  height: 97vh;
  display: flex;
  flex-direction: column;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f5f5;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
}

.message-item.own-message {
  flex-direction: row-reverse;
}

.avatar {
  margin: 0 8px;
}

.message-content {
  max-width: 70%;
}

.message-info {
  margin-bottom: 4px;
  display: flex;
  align-items: center;
}

.username {
  font-size: 12px;
  color: #666;
  margin-right: 8px;
}

.timestamp {
  font-size: 12px;
  color: #999;
}

.bubble {
  position: relative;
  padding: 12px;
  border-radius: 8px;
  background-color: white;
  word-break: break-word;
}

.own-message .bubble {
  background-color: #1989fa;
  color: white;
}

.sending-status {
  position: absolute;
  right: -28px;
  top: 50%;
  transform: translateY(-50%);
}

.status-icon {
  position: absolute;
  right: -28px;
  top: 50%;
  transform: translateY(-50%);
}

.input-area {
  background-color: white;
  padding: 8px;
  border-top: 1px solid #eee;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 8px;
}

.message-input {
  flex: 1;
  padding: 8px;
  border-radius: 20px;
  background-color: #f7f8fa;
}

.send-button {
  height: 40px;
  min-width: 60px;
}
</style>